package com.cloud.custom.tasklist.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.custom.common.context.HumanSession;
import com.cloud.custom.common.result.QkIcon;
import com.cloud.custom.common.result.QkTreeNode;
import com.cloud.custom.common.utils.DateHelper;
import com.cloud.custom.common.utils.MediaStorageHelper;
import com.cloud.custom.common.utils.SessionHelper;
import com.cloud.custom.common.utils.TreeHelper;
import com.cloud.custom.tasklist.entity.TaskListMedia;
import com.cloud.custom.tasklist.mapper.TaskListMediaMapper;
import com.cloud.custom.tasklist.service.TaskListTabMediaService;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class TaskListTabMediaServiceImpl implements TaskListTabMediaService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private TaskListMediaMapper recMediaMapper;

	@Override
	public QkTreeNode[] listMediaTree(long recId, Integer bizId) {
		Example example = new Example(TaskListMedia.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("relationId", recId);
		criteria.andEqualTo("bizId", bizId);
		criteria.andEqualTo("deleteFlag", 0);
		example.orderBy("groupId").asc();
		List<TaskListMedia> medias = recMediaMapper.selectByExample(example);
		List<QkTreeNode> nodes = new ArrayList<QkTreeNode>();
		List<Integer> grpIds = new ArrayList<Integer>();
		for (TaskListMedia media : medias) {
			Integer grpId = media.getGroupId();
			if (!grpIds.contains(grpId)) {
				grpIds.add(grpId);
				QkTreeNode groupNode = new QkTreeNode("g_" + grpId, media.getGroupName());
				groupNode.setLeaf(false);
				groupNode.setSelectable(false);
				groupNode.setRootFlag(true);
				groupNode.setExpanded(true);
				groupNode.setExpandedIcon(QkIcon.FA_FOLDER_OPEN);
				groupNode.setCollapsedIcon(QkIcon.FA_FOLDER);
				nodes.add(groupNode);
			}
			QkTreeNode mediaNode = new QkTreeNode(media.getMediaId(), media.getMediaName());
			mediaNode.setSelectable(true);
			mediaNode.setLeaf(true);
			mediaNode.setSeniorId("g_" + grpId);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("filePath", media.getMediaPath() + media.getMediaName());
			data.put("type", media.getMediaType());
			mediaNode.setData(data);
			// 不同文件类型设置不同的图标
			String mediaName = media.getMediaName().toLowerCase();
			if (mediaName.endsWith("pdf")) {
				mediaNode.setIcon(QkIcon.FA_PDF_O);
			} else if (mediaName.endsWith("doc") || mediaName.endsWith("docx")) {
				mediaNode.setIcon(QkIcon.FA_WORD_O);
			} else if (mediaName.endsWith("jpg") || mediaName.endsWith("png") || mediaName.endsWith("gif")) {
				mediaNode.setIcon(QkIcon.FA_PHOTO_O);
			} else if (mediaName.endsWith("mp4")) {
				mediaNode.setIcon(QkIcon.FA_MOVIE_O);
			} else {
				mediaNode.setIcon(QkIcon.FA_CODE_O);
			}
			nodes.add(mediaNode);
		}
		return TreeHelper.buildList2Tree(nodes);
	}

	@Override
	public void deleteMedia(long mediaId) {
		jdbcTemplate.update(
				"update task_list_media set delete_flag = 1 and delete_time = now() and delete_human_id = ? where media_id = ?",
				SessionHelper.get().getHumanId(), mediaId);
	}

	@Override
	public void uploadMedias(MultipartFile[] files, TaskListMedia media) {
		for (MultipartFile file : files) {
			StringBuilder filePathBuilder = new StringBuilder("/media/")
					.append(DateHelper.dateToFormatStr(new Date(), "yyyyMMdd")).append("/").append(media.getRelationId()).append("/")
					.append(UUID.randomUUID().toString()).append("/");
			try {
				MediaStorageHelper.upload(file.getInputStream(), filePathBuilder.toString() + file.getOriginalFilename());
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			TaskListMedia recMedia = new TaskListMedia();
			String originFileName = file.getOriginalFilename();
			recMedia.setMediaName(originFileName);
			recMedia.setMediaPath(filePathBuilder.toString());
			String mediaName = originFileName.toLowerCase();
			if (mediaName.endsWith("pdf")) {
				recMedia.setMediaType("PDF");
			} else if (mediaName.endsWith("doc") || mediaName.endsWith("docx")) {
				recMedia.setMediaType("WORD");
			} else if (mediaName.endsWith("xls") || mediaName.endsWith("xlsx")) {
				recMedia.setMediaType("EXCEL");
			} else if (mediaName.endsWith("jpg") || mediaName.endsWith("png") || mediaName.endsWith("gif")) {
				recMedia.setMediaType("PIC");
			} else if (mediaName.endsWith("mp4")) {
				recMedia.setMediaType("VIDEO");
			} else if (mediaName.endsWith("mp3")) {
				recMedia.setMediaType("AUDIO");
			}else {
				recMedia.setMediaType("");
			}
			HumanSession humanSession = SessionHelper.get();
			recMedia.setCreateHumanId(humanSession.getHumanId());
			recMedia.setCreateHumanName(humanSession.getHumanName());
			recMedia.setCreateTime(new Date());
			recMedia.setDeleteFlag(0);
			recMedia.setGroupId(media.getGroupId());
			recMedia.setGroupName(media.getGroupName());
			recMedia.setActDefId(media.getActDefId());
			recMedia.setActDefName(media.getActDefName());
			recMedia.setRelationId(media.getRelationId());
			recMedia.setBizId(media.getBizId());
			recMediaMapper.insert(recMedia);
		}
	}

}
